package cn.tedu.eb_film.security;


import cn.tedu.eb_film.mapper.UserMapper;
import cn.tedu.eb_film.pojo.vo.UserVOForLogin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("Spring Security调用了loadUserByUsername()方法,参数为{}", username);
        UserVOForLogin user = userMapper.getByUsername(username);
        log.debug("从数据库中根据【{}】查询信息,查询结果为{}", username, user);
        if (user == null) {
            String message = "用户名或者密码错误";
            log.warn("数据不存在");
            return null;
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
//        List<String> permissions = user.getPermissions();
//        for (String permission : permissions) {
//            authorities.add(new SimpleGrantedAuthority(permission));
//        }
        authorities.add(new SimpleGrantedAuthority("这是一个权限"));

        UserDetailss userDetailss = new UserDetailss(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                (user.getState() == 1),
                authorities
        );
        log.debug("认证通过,返回的类型为{}", userDetailss);
        System.out.println(userDetailss);
        return userDetailss;
    }
}
